import sha1 from 'sha1'
// import getRawBody from 'raw-body'
// import * as util from './util'

export default function (opts) {
  return async function wechatMiddle(ctx, next) {
    const token = opts.token
    const {
      signature,
      nonce,
      timestamp,
      echostr
    } = ctx.query
    const str = [token, timestamp, nonce].sort().join('')
    const sha = sha1(str)

    if(ctx.method === 'GET') {
      if(sha === signature){
        ctx.body = echostr
      }else{
        ctx.body = 'Failed'
      }
    } else if (ctx.method === 'POST') {
      if(sha !== signature){
        ctx.body = 'Failed'

        return false
      }
    }
  }
}